<template>
	<div class="order-batch-list-container margin-top-10">
		<jk-button icon="el-icon-plus" type="primary" class="margin-bottom-4" @click="onAddBatchBtn">生产批号</jk-button>
		<el-tabs v-model="batchTabActive" size="mini" closable type="border-card" @tab-remove="onDeleteTab" @tab-add="onAddBatchBtn">
			<el-tab-pane
				v-for="(tabItem, tabIndex) in tabList"
				:key="tabIndex"
				:label="tabItem.batchCode"
				:name="tabIndex + ''"
				:closable="tabItem.orderBatchPrdNotice.auditState < 2"
			>
				<span slot="label" :style="{color: tabItem.orderBatchPrdNotice.auditState === 3 ? '#19be6b' : '', fontSize: '15px'}">
					<span
						:class="[
							'sort-box',
							batchTabActive === tabIndex + '' ? 'active-sort-item' : '',
							tabItem.orderBatchPrdNotice.auditState === 3 ? 'finish-item' : ''
						]"
					>
						<i v-if="tabItem.orderBatchPrdNotice.auditState === 3" class="el-icon-check" style="font-size: 14px;font-weight: 500;"></i>
						<span v-else>{{ tabIndex + 1 }}</span>
					</span>
					<span>{{ tabItem.batchCode }}</span>
				</span>
				<batch-item-lt-package-info
					:page-type="tabItem.orderBatchPrdNotice.auditState === 3 ? 'detail' : pageType"
					:tab-item="tabItem"
					:form-data="formData"
					:option-data="{
						csColorList,
						xsColorList,
						tubeColorList,
						waistPopeList,
						sealingRopeList,
						labelColorList
					}"
					@return-data="updateDataOfLtPackageInfo($event, tabIndex)"
				></batch-item-lt-package-info>
			</el-tab-pane>
		</el-tabs>
		<select-batch-code-dialog
			:is-demo-yarn="isDemoYarn"
			:demo-yarn-info="demoYarnInfo"
			:selected-list="tabList"
			:form-data="formData"
			api-must-query-prefix="product"
			:dialog-state="selectDialogState"
			@on-visible-change="onVisibleChangeOfSelectDialog"
			@on-confirm="onConfirmBtnOfSelectDialog"
		></select-batch-code-dialog>
		<notice-order-dialog
			:form-data="formData"
			:dialog-state="noticeOrderDialogState"
			@on-visible-change="onVisibleChangeOfNoticeOrderDialogState"
		></notice-order-dialog>
	</div>
</template>
<script>
    import remoteSearchBatchCodeInput
        from '../../../qhPrd/productConfigCotton/components/remote-search-batch-code-input';
    import checkboxPopover from './checkbox-popover';
    import batchItemMaterialList from './batch-item-material-list';
    import { spinTubeColorPage } from '../../../../../api/basicData/tubeColor';
    import batchItemLtPackageInfo from './batch-item-lt-package-info';
    import selectBatchCodeDialog from './radio-select-batch-code-dialog';
    import noticeOrderDialog from '../notice-order-dialog';
    import { tipsBar } from '../../../../../utils/jk/jk-tool';
    import { mathJsAdd, mathJsSub } from '../../../../../utils/jk/jk-cals';

    export default {
        components: {
            noticeOrderDialog,
            selectBatchCodeDialog,
            batchItemLtPackageInfo,
            batchItemMaterialList,
            checkboxPopover,
            remoteSearchBatchCodeInput
        },
        props: {
            pageType: {
                type: String,
                default: ''
            },
            formData: {
                type: Object,
                default() {
                    return {};
                }
            },
            dataList: {
                type: Array,
                default() {
                    return [];
                }
            },
            isDemoYarn: {
                type: Boolean,
                default: false
            },
            demoYarnInfo: {
                type: Object,
                default() {
                    return {};
                }
            }
        },
        data() {
            return {
                batchTabActive: '0',
                noticeOrderDialogState: false,
                selectDialogState: false,
                defaultTabInfo: {
                    'batchCode': '',
                    'batchId': null,
                    'bundleList': [],
                    'coarseSandList': [],
                    'colorId': null,
                    'colorName': '',
                    'id': null,
                    'ifCardboard': true,
                    'ifWord': true,
                    'innerBagList': [],
                    'outerBagList': [],
                    'packageMax': null,
                    'packageMin': null,
                    'packageRemark': '',
                    'packageTypeId': null,
                    'packageTypeName': '',
                    'paperTubeList': [],
                    'sealingRopeList': [],
                    'waistPopeList': [],
                    'wovenBagSpecification': ''
                },
                tabList: [],
                xsColorList: [],
                csColorList: [],
                tubeColorList: [],
                waistPopeList: [],
                sealingRopeList: [],
                labelColorList: [],
                ruleForm: {},
                noticeInfo: {
                    'actualityProductionQty': null,
                    'batchCode': '',
                    'batchId': null,
                    'belongDate': '',
                    'completionQty': null,
                    'dailySupplyQty': null,
                    'dailyYield': null,
                    'efficiencyPercent': null,
                    'gramWeight': null,
                    'ifTest': true,
                    'inputTubeColorList': [],
                    'machineModelCode': '',
                    'machineModelId': null,
                    'machineModelName': '',
                    'machineQty': null,
                    'meters': null,
                    'outputTubeColorList': [],
                    'paperTubeList': [],
                    'planDailyQty': null,
                    'planFinishDate': '',
                    'planMachineQty': null,
                    'planStartDate': '',
                    'ppfCottonBlendingCode': '',
                    'ppfCottonBlendingId': null,
                    'prdNoticeMachineList': [],
                    'processCode': '',
                    'processId': null,
                    'processName': '',
                    'productCode': '',
                    'productId': null,
                    'productModels': '',
                    'productName': '',
                    'productOrderCode': '',
                    'productOrderId': null,
                    'productOrderIssuedCode': '',
                    'productOrderIssuedId': null,
                    'productOrderIssuedQty': null,
                    'productionDailyQty': null,
                    'productionQty': null,
                    'remark': '',
                    'salesCode': '',
                    'specSheetCode': '',
                    'specSheetId': null,
                    'spunYarnBomCode': '',
                    'spunYarnBomId': null,
                    'tenPrice': null,
                    'unitCode': '',
                    'unitId': null,
                    'unitName': '',
                    'workshopCode': '',
                    'workshopId': null,
                    'workshopName': ''
                },
                processList: [],
                workshopList: []
            };
        },
        methods: {
            onVisibleChangeOfNoticeOrderDialogState(e) {
                this.noticeOrderDialogState = e;
            },
            onDeleteTab(e) {
                const hasOpen = this.tabList[Number(e)].orderBatchPrdNotice.prdNoticeMachineList ? this.tabList[Number(e)].orderBatchPrdNotice.prdNoticeMachineList.some(x => x.openingState > 1) : false;
                if (!hasOpen && this.tabList[Number(e)].orderBatchPrdNotice.auditState <= 2) {
                    this.tabList.splice(Number(e), 1);
                    if (this.tabList && this.tabList.length) {
                        this.batchTabActive = '0';
                    }

                    /* // 只有一个排产中的批号时，将剩余的量(生产数量 - 已完成的批号排产数量)累加到该批号身上
                    let count = 0;
                    if (this.tabList) {
                        this.tabList.forEach(batchItem => {
                            if (batchItem.orderBatchPrdNotice.auditState !== 3) {
                                count++;
                            }
                        });
                        if (count && count === 1) {
                            let qty = this.formData.orderQty || 0;
                            this.tabList.forEach(batchItem => {
                                if (batchItem.orderBatchPrdNotice.auditState === 3) {
                                    qty = mathJsSub(qty, batchItem.orderBatchPrdNotice.productionQty || 0);
                                }
                            });

                            this.tabList.forEach(batchItem => {
                                if (batchItem.orderBatchPrdNotice.auditState !== 3) {
                                    this.$set(batchItem.orderBatchPrdNotice, 'productionQty', qty);
                                }
                            });
                        }
                    }*/

                    this.returnData();
                } else {
                    tipsBar(this, 'custom', 'warning', '不能删除已生产或已了机的批号!');
                }
            },
            onVisibleChangeOfSelectDialog(e) {
                this.selectDialogState = e;
            },
            onConfirmBtnOfSelectDialog(e) {
                if (Object.keys(e).length) {
                    let batchItem = {};
                    if (!this.tabList.length) {
                        batchItem = JSON.parse(JSON.stringify(this.defaultTabInfo));
                        batchItem.orderBatchPrdNotice = JSON.parse(JSON.stringify(this.noticeInfo));
                        batchItem.batchId = e.id;
                        batchItem.batchCode = e.batchCode;
                        batchItem.orderBatchPrdNotice = this.addNoticeItem(batchItem);
                    } else {
                        // 新批号的络筒和包装信息，默认复制第一个批号的
                        batchItem = JSON.parse(JSON.stringify(this.tabList[0]));
                        // 因为是新增，需要删除复制过来的ID
                        batchItem.coarseSandList.forEach(x => {
                            delete x.id;
                        });
                        delete batchItem.id;
                        batchItem.orderBatchPrdNotice.auditState = 0;
                        delete batchItem.orderBatchPrdNotice.id;
                        delete batchItem.orderBatchPrdNotice.code;

                        /* batchItem.orderBatchPrdNotice.inputTubeColorList = [];
                        batchItem.orderBatchPrdNotice.outputTubeColorList = [];
                        batchItem.orderBatchPrdNotice.paperTubeList = [];

                        batchItem.waistPopeList = [];
                        batchItem.labelColorList = [];
                        batchItem.paperTubeList = [];*/

                        batchItem.orderBatchPrdNotice.gramWeight = 0;
                        batchItem.orderBatchPrdNotice.meters = 0;
                        /* // 新批号的排产数量 = 生产数量 - 已有批号的排产数量
                        let val = this.formData.orderQty || 0;
                        if (this.formData.productOrderBatchList) {
                            this.formData.productOrderBatchList.forEach(x => {
                                val = mathJsSub(val, x.orderBatchPrdNotice.productionQty || 0);
                            });
                        }*/
                        // 新需求：批次内无发量化排产数量，所以排产数量都改为一致
                        batchItem.orderBatchPrdNotice.productionQty = this.formData.orderQty || 0;

                        batchItem.batchId = e.id;
                        batchItem.batchCode = e.batchCode;
                        batchItem.orderBatchPrdNotice.prdNoticeMachineCloseList = [];
                        if (batchItem.orderBatchPrdNotice && batchItem.orderBatchPrdNotice.prdNoticeMachineList) {
                            batchItem.orderBatchPrdNotice.prdNoticeMachineList.forEach(x => {
                                delete x.id; // 因为是新增，需要删除复制过来的ID
                            });
                        }
                    }
                    this.tabList.push(batchItem);
                    this.selectDialogState = false;
                }
                this.returnData();
            },
            addNoticeItem(batchItem) {
                this.processList = this.$store.state.user.userProcess.processList;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                const noticeInfo = JSON.parse(JSON.stringify(this.noticeInfo));
                noticeInfo.auditState = 0;
                noticeInfo.belongDate = this.formData.orderDate || '';
                const workshopItem = this.$store.state.user.userWorkshop.defaultWorkshopId ? this.workshopList.find(x => x.id === this.$store.state.user.userWorkshop.defaultWorkshopId) : {};
                noticeInfo.workshopId = workshopItem.id || null;
                noticeInfo.workshopCode = workshopItem.code || null;
                noticeInfo.workshopName = workshopItem.name || null;

                const processItem = this.processList.find(x => x.code.toUpperCase() === 'XS') || {};
                noticeInfo.processId = processItem.id || null;
                noticeInfo.processCode = processItem.code || null;
                noticeInfo.processName = processItem.name || null;

                noticeInfo.productId = this.formData.productId || null;
                noticeInfo.productCode = this.formData.productCode || null;
                noticeInfo.productName = this.formData.productName || null;
                noticeInfo.productModels = this.formData.productModels || null;
                noticeInfo.batchId = batchItem.batchId || null;
                noticeInfo.batchCode = batchItem.batchCode || null;
                noticeInfo.productionQty = this.formData.orderQty || 0;
                noticeInfo.ifTest = this.formData.ifTest || false;
                return noticeInfo;
            },
            returnData() {
                this.$emit('update:dataList', JSON.parse(JSON.stringify(this.tabList)));
            },
            onAddBatchBtn() {
                this.selectDialogState = true;
            },
            updateDataOfMaterialList(e, index) {
                this.$set(this.tabList[index], 'coarseSandList', e);
                this.returnData();
            },
            updateDataOfLtPackageInfo(e, index) {
                const arr = this.tabList[index].coarseSandList ? JSON.parse(JSON.stringify(this.tabList[index].coarseSandList)) : [];
                this.$set(this.tabList, [index], {
                    ...e,
                    coarseSandList: arr
                });
                this.returnData();
            },
            getCsColorListRequest() {
                return spinTubeColorPage({ typeCode: 'CS_TUBE_COLOR' }).then(res => {
                    if (res.data.status === 200) {
                        this.csColorList = res.data.res ? res.data.res.map(x => {
                            return {
                                id: x.id,
                                name: x.name
                            };
                        }) : [];
                    }
                });
            },
            getXsColorListRequest() {
                return spinTubeColorPage({ typeCode: 'XS_TUBE_COLOR' }).then(res => {
                    if (res.data.status === 200) {
                        this.xsColorList = res.data.res ? res.data.res.map(x => {
                            return {
                                id: x.id,
                                name: x.name
                            };
                        }) : [];
                    }
                });
            },
            getTubeColorListRequest() {
                return spinTubeColorPage({ typeCode: 'TUBE_COLOR' }).then(res => {
                    if (res.data.status === 200) {
                        this.tubeColorList = res.data.res ? res.data.res.map(x => {
                            return {
                                id: x.id,
                                name: x.name
                            };
                        }) : [];
                    }
                });
            },
            getWaistPopeListRequest() {
                return spinTubeColorPage({ typeCode: 'WAIST_CORD_COLOR' }).then(res => {
                    if (res.data.status === 200) {
                        this.waistPopeList = res.data.res ? res.data.res.map(x => {
                            return {
                                id: x.id,
                                name: x.name
                            };
                        }) : [];
                    }
                });
            },
            getSealingRopeListRequest() {
                return spinTubeColorPage({ typeCode: 'PACKAGING_ROPE_COLOR' }).then(res => {
                    if (res.data.status === 200) {
                        this.sealingRopeList = res.data.res ? res.data.res.map(x => {
                            return {
                                id: x.id,
                                name: x.name
                            };
                        }) : [];
                    }
                });
            },
            getLabelColorListRequest() {
                return spinTubeColorPage({ typeCode: 'LABEL_COLOR_LIST' }).then(res => {
                    if (res.data.status === 200) {
                        this.labelColorList = res.data.res ? res.data.res.map(x => {
                            return {
                                id: x.id,
                                name: x.name
                            };
                        }) : [];
                    }
                });
            },
            async getDependentData() {
                await this.getSealingRopeListRequest();
                await this.getWaistPopeListRequest();
                await this.getXsColorListRequest();
                await this.getCsColorListRequest();
                await this.getTubeColorListRequest();
                await this.getLabelColorListRequest();
            }
        },
        mounted() {
            this.getDependentData();
        },
        destroyed() {
            this.batchTabActive = '0';
        },
        watch: {
            dataList: {
                handler(newVal) {
                    this.tabList = newVal ? JSON.parse(JSON.stringify(newVal)) : [];
                },
                deep: true
            }
        }
    };
</script>
<style scoped lang="scss">
$sort_item_height: 22px;
.sort-box {
    width: $sort_item_height;
    height: $sort_item_height;
    line-height: $sort_item_height;
    border-radius: 50%;
    display: inline-block;
    border: solid 1px #808695;
    text-align: center;
    margin-right: 4px;
}
.active-sort-item {
    border-color: #2d8cf0;
    background: #2d8cf0;
    color: #fff;
}
.finish-item {
    background: #19be6b;
    border-color: #19be6b;
    color: #fff;
}
.order-batch-list-container {
    ::v-deep .el-tabs__item {
        padding: 0 20px;
        height: 40px;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        line-height: 40px;
        display: inline-block;
        list-style: none;
        font-size: 14px;
        font-weight: 500;
        color: #515a6e;
        position: relative;
    }
    ::v-deep .el-tabs--card > .el-tabs__header .el-tabs__item.is-active.is-closable {
        padding-left: 20px;
        padding-right: 20px;
        color: #fff;
        background: #2d8cf0;
    }
    ::v-deep .el-tabs--border-card > .el-tabs__header {
        height: 39px;
    }
    ::v-deep .el-tabs--border-card > .el-tabs__header > .el-tabs__new-tab {
        float: right;
        border: 1px solid #2d8cf0;
        height: 18px;
        width: 18px;
        line-height: 18px;
        margin: 11px 15px 9px 10px;
        border-radius: 3px;
        text-align: center;
        font-size: 12px;
        color: #2d8cf0;
        cursor: pointer;
        -webkit-transition: all 0.15s;
        transition: all 0.15s;
    }
}
</style>
